var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors= require('cors')
var app = express();

//实时通信
const WebSocket = require('ws'); 
const http = require('http'); 

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors())
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


const server = http.createServer((req, res) => {  
  res.writeHead(200, { 'Content-Type': 'text/plain' });  
  res.end('WebSocket server is running\n');  
});  
  
// 创建一个WebSocket服务器实例，并监听连接事件  
const wss = new WebSocket.Server({ server });  
  
wss.on('connection', (ws) => {  
  console.log('Client connected');  
  
  // 当接收到消息时，广播给所有连接的客户端  
  ws.on('message', (message) => {  
    console.log(`Received message: ${message}`);  
    wss.clients.forEach((client) => {  
      if (client.readyState === WebSocket.OPEN) {  
        client.send(message);  
      }  
    });  
  });  
  
  // 当客户端断开连接时  
  ws.on('close', () => {  
    console.log('Client disconnected');  
  });  
  
  // 当发生错误时  
  ws.on('error', (error) => {  
    console.error(`WebSocket error: ${error}`);  
  });  
});  
  
// 设置服务器监听的端口  
const PORT = process.env.PORT || 5000;  
server.listen(PORT, () => {  
  console.log(`Server is listening on port ${PORT}`);  
});

module.exports = app;
